/**
 * 菜单管理页面
 */
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { Button, Input, Modal } from '../../components';
import request from '../../utils/request';
import { useTranslation } from '@/utils/i18n'
import { useThemeStore } from '@/stores/themeStore'
// 菜单数据接口定义
export interface MenuItem {
  id: number;
  name: string;
  path: string;
  icon: string;
  parentId: number;
  level: number;
  order: number;
  component: string;
  hidden: boolean;
  status: '启用' | '禁用';
  createTime: string;
  updateTime: string;
  children?: MenuItem[];
}

// 菜单表单数据接口
interface MenuFormData {
  name: string;
  path: string;
  icon: string;
  parentId: number;
  level: number;
  order: number;
  component: string;
  hidden: boolean;
  status: '启用' | '禁用';
}

// 分页参数接口
interface PaginationParams {
  pageNum: number;
  pageSize: number;
}

const MenuManage: React.FC = () => {
  const { t } = useTranslation()
  const themePreference = useThemeStore((state) => state.theme)
  const isDark = useMemo(() => {
    if (themePreference === 'dark') return true
    if (themePreference === 'light') return false
    return window.matchMedia('(prefers-color-scheme: dark)').matches
  }, [themePreference])
  const containerClass = `flex flex-col min-h-screen px-6 py-6 transition-colors ${isDark ? 'bg-slate-900 text-slate-100' : 'bg-white text-gray-900'}`
  const toolbarClass = `bg-white dark:bg-slate-800 rounded-lg shadow p-4 mb-6 flex flex-wrap items-center justify-between gap-4 transition-colors`
  const tableWrapperClass = `flex-1 bg-white dark:bg-slate-800 rounded-lg shadow overflow-hidden transition-colors`
  // 状态管理
  const [menus, setMenus] = useState<MenuItem[]>([]);
  const [allMenus, setAllMenus] = useState<MenuItem[]>([]); // 用于选择父菜单
  const [loading, setLoading] = useState<boolean>(false);
  const [modalOpen, setModalOpen] = useState<boolean>(false);
  const [editingMenu, setEditingMenu] = useState<MenuItem | null>(null);
  const [pagination, setPagination] = useState<PaginationParams>({
    pageNum: 1,
    pageSize: 10
  });
  const [total, setTotal] = useState<number>(0);
  const [searchKeyword, setSearchKeyword] = useState<string>('');
  const [selectedMenuIds, setSelectedMenuIds] = useState<number[]>([]); // 用于批量操作
  
  // 表单数据
  const [formData, setFormData] = useState<MenuFormData>({
    name: '',
    path: '',
    icon: '',
    parentId: 0,
    level: 1,
    order: 0,
    component: '',
    hidden: false,
    status: '启用'
  });
  
  // 表单错误
  const [formErrors, setFormErrors] = useState<Partial<Record<keyof MenuFormData, string>>>({});
  const [feedback, setFeedback] = useState<{ type: 'success' | 'error' | 'info'; message: string } | null>(null)

  const getErrorMessage = useCallback((error: unknown) => {
    if (error && typeof error === 'object' && 'message' in error) {
      const message = (error as { message?: string }).message
      if (typeof message === 'string' && message.trim()) {
        return message
      }
    }
    if (error instanceof Error && error.message) {
      return error.message
    }
    return t('common.unknownError')
  }, [t])

  const showFeedback = useCallback((type: 'success' | 'error' | 'info', message: string) => {
    setFeedback({ type, message })
  }, [])

  const clearErrorFeedback = useCallback(() => {
    setFeedback(prev => (prev?.type === 'error' ? null : prev))
  }, [])
 
  // 获取菜单列表 - 使用useCallback避免不必要的重渲染
  const fetchMenus = useCallback(async (pageNum: number, pageSize: number) => {
    try {
      setLoading(true);
      const response = await request.get<{ list: MenuItem[]; total: number; pageNum: number; pageSize: number }>(
        '/api/hzl/menu/list',
        {
          pageNum,
          pageSize
        }
      );

      setMenus(response.data.list ?? []);
      setTotal(response.data.total ?? 0);
      clearErrorFeedback()
    } catch (error: unknown) {
      console.error('获取菜单列表失败:', error);
      showFeedback('error', t('menu.fetchFailed', { error: getErrorMessage(error) }))
    } finally {
      setLoading(false);
    }
  }, [clearErrorFeedback, getErrorMessage, showFeedback, t]);

  // 获取所有菜单（用于选择父菜单） - 使用useCallback避免不必要的重渲染
  const fetchAllMenus = useCallback(async () => {
    try {
      const response = await request.get<MenuItem[]>('/api/hzl/menu/tree');
      setAllMenus(response.data || []);
    } catch (error: unknown) {
      console.error('获取所有菜单失败:', error);
    }
  }, []);



  // 切换菜单状态
  const toggleMenuStatus = async (id: number) => {
    try {
      setLoading(true);
      await request.put<{ success: boolean }>(`/api/hzl/menu/toggle/${id}`);
      
      showFeedback('success', t('menu.toggleSuccess'))
      fetchMenus(pagination.pageNum, pagination.pageSize);
      return true;
    } catch (error: unknown) {
      console.error('切换菜单状态失败:', error);
      showFeedback('error', t('menu.toggleFailed', { error: getErrorMessage(error) }))
    } finally {
      setLoading(false);
    }
    return false;
  };

  // 搜索菜单
  const searchMenus = async (keyword: string) => {
    try {
      setLoading(true);
      const response = await request.get<{ list: MenuItem[]; total: number; pageNum: number; pageSize: number }>(
        '/api/hzl/menu/search',
        {
          keyword,
          pageNum: 1,
          pageSize: pagination.pageSize
        }
      );

      setMenus(response.data.list ?? []);
      setTotal(response.data.total ?? 0);
      setPagination(prev => ({
        ...prev,
        pageNum: response.data.pageNum ?? 1,
        pageSize: response.data.pageSize ?? prev.pageSize
      }));
      clearErrorFeedback()
    } catch (error: unknown) {
      console.error('搜索菜单失败:', error);
      showFeedback('error', t('menu.searchFailed', { error: getErrorMessage(error) }))
    } finally {
      setLoading(false);
    }
  };





  // 导出菜单数据
  const exportMenus = async () => {
    try {
      const response = await request.get<MenuItem[]>('/api/hzl/menu/export');
      const exportPayload = {
        exportedAt: new Date().toISOString(),
        total: response.data.length,
        data: response.data
      };
      const blob = new Blob([JSON.stringify(exportPayload, null, 2)], { type: 'application/json' });
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `menus_${Date.now()}.json`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      showFeedback('success', t('menu.exportSuccess'))
    } catch (error: unknown) {
      console.error('导出菜单数据失败:', error);
      showFeedback('error', t('menu.exportFailed', { error: getErrorMessage(error) }))
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchMenus(pagination.pageNum, pagination.pageSize);
    fetchAllMenus();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pagination.pageNum, pagination.pageSize, fetchAllMenus]);

  // 表单验证
  const validateForm = (): boolean => {
    const errors: Partial<Record<keyof MenuFormData, string>> = {};
    
    if (!formData.name.trim()) {
      errors.name = t('menu.validation.nameRequired');
    }
    
    if (!formData.path.trim()) {
      errors.path = t('menu.validation.pathRequired');
    }
    
    if (!formData.component.trim()) {
      errors.component = t('menu.validation.componentRequired');
    }
    
    setFormErrors(errors);
    return Object.keys(errors).length === 0;
  };

  // 打开添加菜单弹窗
  const handleAddMenu = () => {
    setEditingMenu(null);
    setFormData({
      name: '',
      path: '',
      icon: '',
      parentId: 0,
      level: 1,
      order: 0,
      component: '',
      hidden: false,
      status: '启用'
    });
    setFormErrors({});
    setModalOpen(true);
  };

  // 打开编辑菜单弹窗
  const handleEditMenu = (menu: MenuItem) => {
    setEditingMenu(menu);
    setFormData({
      name: menu.name,
      path: menu.path,
      icon: menu.icon,
      parentId: menu.parentId,
      level: menu.level,
      order: menu.order,
      component: menu.component,
      hidden: menu.hidden,
      status: menu.status
    });
    setFormErrors({});
    setModalOpen(true);
  };

  // 关闭弹窗
  const handleCloseModal = () => {
    setModalOpen(false);
    setEditingMenu(null);
    setFormErrors({});
  };

  // 处理表单输入变化
  const handleInputChange = (field: keyof MenuFormData, value: string | number | boolean) => {
    setFormData(prev => ({ ...prev, [field]: value }));
    // 清除对应字段的错误
    if (formErrors[field]) {
      setFormErrors(prev => ({ ...prev, [field]: undefined }));
    }
    
    // 如果修改了父菜单，自动计算级别
    if (field === 'parentId') {
      const parentIdValue = Number(value);
      if (parentIdValue === 0) {
        setFormData(prev => ({ ...prev, level: 1 }));
      } else {
        const parentMenu = allMenus.find(m => m.id === parentIdValue);
        if (parentMenu) {
          setFormData(prev => ({ ...prev, level: parentMenu.level + 1 }));
        }
      }
    }
  };

  // 提交表单
  const handleSubmit = async () => {
    if (!validateForm()) {
      return;
    }

    try {
      setLoading(true);
      
      if (editingMenu) {
        // 更新菜单
        await request.put<{ success: boolean }>(`/api/hzl/menu/update/${editingMenu.id}`, formData);
        showFeedback('success', t('menu.updateSuccess'))
        fetchMenus(pagination.pageNum, pagination.pageSize);
        handleCloseModal();
      } else {
        // 添加菜单
        await request.post<{ success: boolean }>('/api/hzl/menu/add', formData);
        showFeedback('success', t('menu.addSuccess'))
        fetchMenus(pagination.pageNum, pagination.pageSize);
        fetchAllMenus(); // 更新父菜单列表
        handleCloseModal();
      }
    } catch (error: unknown) {
      console.error('保存菜单失败:', error);
      const errorMessage = getErrorMessage(error);
      showFeedback('error', editingMenu ? t('menu.updateFailed', { error: errorMessage }) : t('menu.addFailed', { error: errorMessage }))
    } finally {
      setLoading(false);
    }
  };

  // 删除菜单
  const handleDeleteMenu = async (menuId: number) => {
    if (!window.confirm(t('menu.deleteConfirm'))) {
      return;
    }

    try {
      setLoading(true);
      await request.delete<{ success: boolean }>(`/api/hzl/menu/delete/${menuId}`);
      
      showFeedback('success', t('menu.deleteSuccess'))
      fetchMenus(pagination.pageNum, pagination.pageSize);
      fetchAllMenus(); // 更新父菜单列表
    } catch (error: unknown) {
      console.error('删除菜单失败:', error);
      showFeedback('error', t('menu.deleteFailed', { error: getErrorMessage(error) }))
    } finally {
      setLoading(false);
    }
  };

  // 批量删除菜单
  const batchDeleteMenus = async (ids: number[]) => {
    if (!ids || ids.length === 0) {
      showFeedback('info', t('menu.batchDeleteEmpty'))
      return;
    }
    
    if (!window.confirm(t('menu.batchDeleteConfirm', { count: ids.length }))) {
      return;
    }

    try {
      setLoading(true);
      await request.post<{ success: boolean }>('/api/hzl/menu/batchDelete', { ids });
      
      showFeedback('success', t('menu.batchDeleteSuccess'))
      fetchMenus(pagination.pageNum, pagination.pageSize);
      fetchAllMenus();
    } catch (error: unknown) {
      console.error('批量删除菜单失败:', error);
      showFeedback('error', t('menu.batchDeleteFailed', { error: getErrorMessage(error) }))
    } finally {
      setLoading(false);
    }
  };
  
  // 处理菜单状态切换
  const handleToggleStatus = async (menuId: number) => {
    await toggleMenuStatus(menuId);
  };
  
  // 处理导出菜单
  const handleExportMenus = () => {
    exportMenus();
  };

  // 处理分页变化
  const handlePageChange = (newPage: number) => {
    setPagination(prev => ({ ...prev, pageNum: newPage }));
    fetchMenus(newPage, pagination.pageSize);
  };

  // 处理搜索
  const handleSearch = () => {
    if (searchKeyword.trim()) {
      searchMenus(searchKeyword);
    } else {
      fetchMenus(pagination.pageNum, pagination.pageSize);
    }
  };

  // 重置搜索
  const handleResetSearch = () => {
    setSearchKeyword('');
    setPagination(prev => ({ ...prev, pageNum: 1 }));
    fetchMenus(1, pagination.pageSize);
  };

  // 格式化状态显示
  const formatStatus = (status: string) => {
    const baseClass = 'inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium transition-colors'
    return status === '启用' ? (
      <span className={`${baseClass} bg-green-100 text-green-800 dark:bg-green-500/20 dark:text-green-200`}>
        {t('menu.toggleEnable')}
      </span>
    ) : (
      <span className={`${baseClass} bg-red-100 text-red-800 dark:bg-red-500/20 dark:text-red-200`}>
        {t('menu.toggleDisable')}
      </span>
    );
  };

  // 格式化布尔值显示
  const formatBoolean = (value: boolean) => {
    return value ? (
      <span className="text-green-600 dark:text-green-300">{t('menu.boolean.yes')}</span>
    ) : (
      <span className="text-gray-400 dark:text-slate-400">{t('menu.boolean.no')}</span>
    );
  };

  // 获取父菜单名称
  const getParentMenuName = (parentId: number) => {
    if (parentId === 0) return t('menu.parent.top');
    const parent = allMenus.find(m => m.id === parentId);
    return parent?.name || t('menu.parent.unknown');
  };

  return (
    <div className={containerClass}>
      {feedback && (
        <div
          className={`mb-4 rounded-lg border px-4 py-3 text-sm transition-colors ${feedback.type === 'error'
            ? 'border-red-500/40 bg-red-500/10 text-red-200'
            : feedback.type === 'success'
              ? 'border-green-500/40 bg-green-500/10 text-green-200'
              : 'border-blue-500/40 bg-blue-500/10 text-blue-200'
            }`}
        >
          <div className="flex items-start justify-between gap-4">
            <span>{feedback.message}</span>
            <button
              type="button"
              onClick={() => setFeedback(null)}
              className="text-xs font-semibold uppercase tracking-wide hover:opacity-80"
            >
              Close
            </button>
          </div>
        </div>
      )}
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-800 dark:text-slate-100">{t('menu.title')}</h2>
        <p className="text-gray-500 dark:text-slate-400 mt-1">{t('menu.subtitle')}</p>
      </div>

      {/* 操作栏 */}
      <div className={toolbarClass}>
        <div className="flex flex-wrap gap-4 items-center">
          <Button onClick={handleAddMenu} variant="primary" size="md">
            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
              <path fillRule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clipRule="evenodd" />
            </svg>
            {t('menu.add')}
          </Button>
          <Button onClick={handleExportMenus} variant="secondary" size="md">
            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
              <path fillRule="evenodd" d="M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm3.293-7.707a1 1 0 011.414 0L9 10.586V3a1 1 0 112 0v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z" clipRule="evenodd" />
            </svg>
            {t('menu.export')}
          </Button>
          <Button 
            onClick={() => batchDeleteMenus(selectedMenuIds)}
            variant="danger" 
            size="md"
            disabled={selectedMenuIds.length === 0}
          >
            <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 mr-2" viewBox="0 0 20 20" fill="currentColor">
              <path fillRule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clipRule="evenodd" />
            </svg>
            {t('menu.batchDeleteWithCount', { count: selectedMenuIds.length })}
          </Button>
        </div>
        
        <div className="flex items-center gap-2">
          <Input
            placeholder={t('menu.searchPlaceholder')}
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            className="w-64 border border-gray-300 dark:border-slate-600 bg-white dark:bg-slate-700 text-gray-900 dark:text-slate-100"
          />
          <Button onClick={handleSearch} variant="secondary" size="sm">
            {t('common.search')}
          </Button>
          <Button onClick={handleResetSearch} variant="outline" size="sm">
            {t('common.reset')}
          </Button>
        </div>
      </div>

      {/* 菜单表格 */}
      <div className={tableWrapperClass}>
        <div className="overflow-x-auto">
          <table className={`min-w-full divide-y divide-gray-200 dark:divide-slate-700 text-gray-800 dark:text-slate-100 ${isDark ? '' : 'bg-white'}`}>
            <thead className={`${isDark ? 'bg-slate-900/70 text-slate-100' : 'bg-slate-200 text-slate-700'} transition-colors`}>
              <tr>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-slate-300 uppercase tracking-wider">
                  <input
                    type="checkbox"
                    checked={selectedMenuIds.length === menus.length && menus.length > 0}
                    onChange={(e) => {
                      if (e.target.checked) {
                        setSelectedMenuIds(menus.map(menu => menu.id));
                      } else {
                        setSelectedMenuIds([]);
                      }
                    }}
                    className="h-4 w-4 text-indigo-600 border-gray-300 rounded"
                  />
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-slate-300 uppercase tracking-wider">
                  {t('menu.table.id')}
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-slate-300 uppercase tracking-wider">
                  {t('menu.table.name')}
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-slate-300 uppercase tracking-wider">
                  {t('menu.table.path')}
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-slate-300 uppercase tracking-wider">
                  {t('menu.table.parent')}
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-slate-300 uppercase tracking-wider">
                  {t('menu.table.level')}
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-slate-300 uppercase tracking-wider">
                  {t('menu.table.order')}
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-slate-300 uppercase tracking-wider">
                  {t('menu.table.hidden')}
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-slate-300 uppercase tracking-wider">
                  {t('menu.table.status')}
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-slate-300 uppercase tracking-wider">
                  {t('menu.table.createTime')}
                </th>
                <th scope="col" className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-slate-300 uppercase tracking-wider">
                  {t('menu.table.actions')}
                </th>
              </tr>
            </thead>
            <tbody className={isDark ? 'bg-slate-800 divide-y divide-slate-700 transition-colors' : 'bg-white divide-y divide-gray-200 transition-colors'}>
              {loading ? (
                <tr>
                  <td colSpan={11} className="px-6 py-4 text-center text-gray-600 dark:text-slate-300">
                    {t('common.loading')}
                  </td>
                </tr>
              ) : menus.length === 0 ? (
                <tr>
                  <td colSpan={11} className="px-6 py-4 text-center text-gray-500 dark:text-slate-300">
                    {t('menu.empty')}
                  </td>
                </tr>
              ) : (
                menus.map((menu) => (
                  <tr key={menu.id} className="bg-white dark:bg-slate-800 hover:bg-blue-50/80 dark:hover:bg-blue-500/10 transition-colors">
                    <td className="px-6 py-4 whitespace-nowrap">
                      <input
                        type="checkbox"
                        checked={selectedMenuIds.includes(menu.id)}
                        onChange={(e) => {
                          if (e.target.checked) {
                            setSelectedMenuIds([...selectedMenuIds, menu.id]);
                          } else {
                            setSelectedMenuIds(selectedMenuIds.filter(id => id !== menu.id));
                          }
                        }}
                        className="h-4 w-4 text-indigo-600 border-gray-300 rounded"
                      />
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-slate-100">
                      {menu.id}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center">
                        {menu.icon && (
                          <span className="text-gray-500 dark:text-slate-300 mr-2">{menu.icon}</span>
                        )}
                        <div className="text-sm font-medium text-gray-900 dark:text-slate-100">
                          {menu.name}
                        </div>
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-slate-300">
                      {menu.path}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-slate-300">
                      {getParentMenuName(menu.parentId)}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-slate-300">
                      {menu.level}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-slate-300">
                      {menu.order}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      {formatBoolean(menu.hidden)}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      {formatStatus(menu.status)}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-slate-300">
                      {new Date(menu.createTime).toLocaleString()}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                      <button
                        onClick={() => handleEditMenu(menu)}
                        className="text-blue-600 hover:text-blue-900 dark:text-blue-300 dark:hover:text-blue-200 mr-3"
                      >
                        {t('common.edit')}
                      </button>
                      <button
                        onClick={() => handleToggleStatus(menu.id)}
                        className={`mr-3 ${menu.status === '启用' ? 'text-orange-600 hover:text-orange-900 dark:text-orange-300 dark:hover:text-orange-200' : 'text-green-600 hover:text-green-900 dark:text-green-300 dark:hover:text-green-200'}`}
                      >
                        {menu.status === '启用' ? t('menu.toggleDisable') : t('menu.toggleEnable')}
                      </button>
                      <button
                        onClick={() => handleDeleteMenu(menu.id)}
                        className="text-red-600 hover:text-red-900 dark:text-red-300 dark:hover:text-red-200"
                      >
                        {t('common.delete')}
                      </button>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* 分页 */}
        {!searchKeyword && (
          <div className={`px-6 py-4 border-t ${isDark ? 'border-slate-700 bg-slate-900/70 text-slate-200' : 'border-gray-200 bg-slate-100 text-gray-800'} flex items-center justify-between transition-colors`}>
            <div className="text-sm text-gray-700 dark:text-slate-300">
              {t('menu.total', { count: total })}
            </div>
            <div className="flex items-center space-x-2">
              <Button
                onClick={() => handlePageChange(pagination.pageNum - 1)}
                disabled={pagination.pageNum === 1}
                variant="outline"
                size="sm"
              >
                {t('common.prevPage')}
              </Button>
              <span className="text-sm text-gray-700 dark:text-slate-300">
                {t('common.pageIndicator', { page: pagination.pageNum })}
              </span>
              <Button
                onClick={() => handlePageChange(pagination.pageNum + 1)}
                disabled={pagination.pageNum * pagination.pageSize >= total}
                variant="outline"
                size="sm"
              >
                {t('common.nextPage')}
              </Button>
            </div>
          </div>
        )}
      </div>

      {/* 添加/编辑菜单弹窗 */}
      <Modal
        isOpen={modalOpen}
        onClose={handleCloseModal}
        title={editingMenu ? t('menu.edit') : t('menu.add')}
        size="lg"
      >
        <div className="space-y-6 text-gray-800 dark:text-slate-100">
          {/* 基础信息 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* 菜单名称 */}
            <div>
              <Input
                label={t('menu.form.nameLabel')}
                value={formData.name}
                onChange={(e) => handleInputChange('name', e.target.value)}
                error={formErrors.name}
                placeholder={t('menu.form.namePlaceholder')}
              />
            </div>
            
            {/* 菜单路径 */}
            <div>
              <Input
                label={t('menu.form.pathLabel')}
                value={formData.path}
                onChange={(e) => handleInputChange('path', e.target.value)}
                error={formErrors.path}
                placeholder={t('menu.form.pathPlaceholder')}
              />
            </div>
            
            {/* 组件路径 */}
            <div>
              <Input
                label={t('menu.form.componentLabel')}
                value={formData.component}
                onChange={(e) => handleInputChange('component', e.target.value)}
                error={formErrors.component}
                placeholder={t('menu.form.componentPlaceholder')}
              />
            </div>
            
            {/* 菜单图标 */}
            <div>
              <Input
                label={t('menu.form.iconLabel')}
                value={formData.icon}
                onChange={(e) => handleInputChange('icon', e.target.value)}
                placeholder={t('menu.form.iconPlaceholder')}
              />
            </div>
            
            {/* 父菜单 */}
            <div>
              <label className="block text-sm font-semibold text-gray-700 dark:text-slate-200 mb-2">
                {t('menu.form.parentLabel')}
              </label>
              <select
                className="w-full px-4 py-2.5 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-blue-400 bg-white dark:bg-slate-800 dark:border-slate-600 dark:text-slate-100"
                value={formData.parentId}
                onChange={(e) => handleInputChange('parentId', parseInt(e.target.value))}
              >
                <option value={0}>{t('menu.parent.top')}</option>
                {allMenus
                  .filter(menu => !editingMenu || menu.id !== editingMenu.id) // 排除自己作为父菜单
                  .filter(menu => menu.level < 3) // 限制最多3级菜单
                  .map((menu) => (
                    <option key={menu.id} value={menu.id}>
                      {getParentMenuName(menu.parentId)} / {menu.name}
                    </option>
                  ))
                }
              </select>
            </div>
            
            {/* 排序 */}
            <div>
              <Input
                label={t('menu.form.orderLabel')}
                type="number"
                value={formData.order}
                onChange={(e) => handleInputChange('order', parseInt(e.target.value) || 0)}
                placeholder={t('menu.form.orderPlaceholder')}
              />
            </div>
          </div>
          
          {/* 高级设置 */}
          <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
            {/* 是否隐藏 */}
            <div className="flex items-center">
              <input
                type="checkbox"
                id="hidden"
                checked={formData.hidden}
                onChange={(e) => handleInputChange('hidden', e.target.checked)}
                className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
              />
              <label htmlFor="hidden" className="ml-2 block text-sm text-gray-700 dark:text-slate-200">
                {t('menu.form.hiddenLabel')}
              </label>
            </div>
            
            {/* 状态 */}
            <div>
              <label className="block text-sm font-semibold text-gray-700 dark:text-slate-200 mb-2">
                {t('menu.form.statusLabel')}
              </label>
              <select
                className="w-full px-4 py-2.5 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500/50 focus:border-blue-400 bg-white dark:bg-slate-800 dark:border-slate-600 dark:text-slate-100"
                value={formData.status}
                onChange={(e) => handleInputChange('status', e.target.value)}
              >
                <option value="启用">{t('menu.toggleEnable')}</option>
                <option value="禁用">{t('menu.toggleDisable')}</option>
              </select>
            </div>
          </div>
          
          {/* 级别显示（只读） */}
          <div className="text-sm text-gray-500 dark:text-slate-300">
            {t('menu.form.levelInfo', { level: formData.level })}
          </div>
        </div>
        
        {/* 操作按钮 */}
        <div className="mt-8 flex justify-end gap-4">
          <Button onClick={handleCloseModal} variant="outline">
            {t('common.cancel')}
          </Button>
          <Button onClick={handleSubmit} variant="primary" loading={loading}>
            {editingMenu ? t('menu.form.submitUpdate') : t('menu.form.submitAdd')}
          </Button>
        </div>
      </Modal>
    </div>
  )
}

export default MenuManage
